package com.tongfusoft.web.core.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.utils.Logger;
import com.tongfusoft.utils.MapUtils;
import com.tongfusoft.utils.web.WebUtils;
import com.tongfusoft.web.core.Constant;
import com.tongfusoft.web.core.data.DFileInfo;
import com.tongfusoft.web.core.data.User;
import com.tongfusoft.web.core.service.IDownLoadFileService;

public class DownloadFileServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7016527343423354176L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		boolean result = false;
		String message = "";
		InputStream fis = null;
		OutputStream toClient = null;
		DFileInfo fileInfo = null;
		try {
			WebApplicationContext bean = WebApplicationContextUtils
					.getRequiredWebApplicationContext(this.getServletContext());

			Map param = WebUtils.getRequestParameters(request);
			MapUtils.copyMap(param, WebUtils.getApplicationAttributes(request));
			IDownLoadFileService dFileService = (IDownLoadFileService) bean
					.getBean(String.valueOf(param.get("beanId")));
			fileInfo = dFileService.downLoadFileInfo(param, (User) request
					.getSession().getAttribute(Constant.SESSION_USER));
			if (fileInfo == null) {
				throw new ServiceException("error");
			} else {
				if (StringUtils.isEmpty(fileInfo.getFilePath()))
					throw new ServiceException("error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error(e.getMessage(), e);
			result = false;
			message = "common.prompt.fail";
		}

		try {

			String filePath = fileInfo.getFilePath();
			File file = new File(filePath);
			fis = new BufferedInputStream(new FileInputStream(filePath));
			byte[] buffer = new byte[1024];
			int bytesRead;

			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename="
					+ new String(fileInfo.getFileName().getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
				toClient.write(buffer, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error(e.getMessage());
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			if (toClient != null) {
				try {
					toClient.flush();
					toClient.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}

			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		doGet(request, response);
	}
}
